package cn.edu.whut.commonapi.core.api;


import cn.edu.whut.commonapi.core.error.CommonErrorCodes;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;


/**
 * api接口返回信息封装
 */
@Schema(description = "API接口返回信息封装")
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class ApiResult<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    @Schema(description = "状态码")
    private Integer code;

    /**
     * 提示信息
     */
    @Schema(description = "响应信息")
    private String msg;

    /**
     * 数据
     */
    @Schema(description = "数据")
    private T data;

    public ApiResult(){

    }

    public ApiResult(int code, String msg){
        this.code = code;
        this.msg = msg;
    }

    public ApiResult(int code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ApiResult(T data){
        this.code = CommonErrorCodes.SUCCESS.code();
        this.msg = CommonErrorCodes.SUCCESS.msg();
        this.data = data;
    }

    public ApiResult(CommonErrorCodes errorCode, T data) {
        this.code = errorCode.code();
        this.msg = errorCode.msg();
        this.data = data;
    }

    public static <T> ApiResult<T> success(T data){
        return (ApiResult<T>) new ApiResult(data);
    }

    public static <T> ApiResult<T> success(){
        return (ApiResult<T>) new ApiResult(CommonErrorCodes.SUCCESS.code(), CommonErrorCodes.SUCCESS.msg());
    }

    public static <T> ApiResult<T> error(int code, String msg){
        return new ApiResult<>(code, msg);
    }

    public static <T> ApiResult<T> error(CommonErrorCodes errorCode){
        return new ApiResult<>(errorCode, null);
    }

}
